import Vue from 'vue'
//对应你要跳转的组件
import Router from 'vue-router'
// 在router中以路由的形式将login组件渲染到App根组件中
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/User.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate.vue'
import Params from '../components/goods/Params.vue'

Vue.use(Router)

// 将路由暴露出来
const router = new Router({
    // 在路由数组中新增一个路由规则
    routes: [
        { path: '/', redirect: '/login' }, // 访问根路径时自动重定向到登录界面
        { path: '/login', component: Login },
        {
            path: '/home',
            component: Home,
            redirect: '/welcome',
            // '/home'的子路由
            children: [
                { path: '/welcome', component: Welcome },
                { path: '/users', component: User },
                { path: '/rights', component: Rights },
                { path: '/roles', component: Roles },
                { path: '/categories', component: Cate },
                { path: '/params', component: Params },
            ]
        },
    ]
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // to 将要访问的路径
    // from：代表从哪个路径来
    // next：是一个函数，表示放行
    console.log('路由导航守卫执行->' + to.path);
    if (to.path == '/login') return next()
    // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
    if (!tokenStr) return next('/login') // 说明没有登录，强制跳转登录界面
    next()
})

export default router